package com.cdutetc.demo.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.cdutetc.demo.repository.UserRepository;
import com.cdutetc.demo.service.UserService;
import com.cdutetc.demo.common.Result;
import com.cdutetc.demo.common.ResultCode;
import com.cdutetc.demo.model.entity.User;
import com.cdutetc.demo.model.ao.UserQueryAO;

import jakarta.transaction.Transactional;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired // 自动装配，即由springboot帮我们创建该对象，并传递给userRespository
    private  UserRepository userRepository;

    @Autowired
    private UserService userService;

    // 获取所有用户
    @GetMapping
    public Result<List<User>> getAllUsers(){
        List<User> users = userRepository.findAll();
        return Result.success(users);
    }
    // 分页查询用户
    @GetMapping("/page")
    public Result<?> getUsers(@Validated UserQueryAO queryAO){

        return userService.queryUsers(queryAO);

    }
    // 获取单个用户
    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Long id){
        User user = userRepository.findById(id).orElse(null);
        if(user == null) {
            return Result.fail(ResultCode.NOT_FOUND);
        }
        return Result.success(user);
    }

    // 创建用户
    @PostMapping
    @Transactional
    public Result<User> addUser(@RequestBody User user){
        User saved = userRepository.save(user);
        return Result.success(saved);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    @Transactional
    public Result<Void> deleteUser(@PathVariable Long id){
        if(!userRepository.existsById(id)) {
            return Result.fail(ResultCode.NOT_FOUND);
        }
        userRepository.deleteById(id);
        return Result.success();
    }

    // 更新用户
    // 更新用户（修复版本）
    @PutMapping("/{id}")
    @Transactional
    public Result<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        User exist = userRepository.findById(id).orElse(null);
        if (exist == null) {
            return Result.fail(ResultCode.NOT_FOUND);
        }

        // 只更新允许修改的字段
        if (user.getUsername() != null) {
            exist.setUsername(user.getUsername());
        }
        if (user.getEmail() != null) {
            exist.setEmail(user.getEmail());
        }
        if (user.getNickname() != null) {
            exist.setNickname(user.getNickname());
        }
        // 移除 getAge() 相关代码，因为 User 实体中没有 age 字段

        User updated = userRepository.save(exist);
        return Result.success(updated);
    }

    
}